﻿using Microsoft.EntityFrameworkCore;
using mozhi.smarterp.AuthorCenter.EntityFrameworkCore;
using mozhi.smarterp.AuthorCenter.Users.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore;

namespace mozhi.smarterp.AuthorCenter.Users
{
    public class UserTenantRepository : EfCoreRepository<AuthorCenterDbContext, UserTenant, Guid>, IUserTenantRepository
    {
        public UserTenantRepository(IDbContextProvider<AuthorCenterDbContext> dbContextProvider) : base(dbContextProvider)
        {
        }

        public async Task<int> GetCountAsync(Guid? userId, Guid? tenantId, CancellationToken cancellationToken = default)
        {
            var dbContext = await GetDbContextAsync();

            int count = await dbContext.Set<UserTenant>().AsNoTracking()
                .WhereIf(userId.HasValue , x=>x.UserId == userId)
                .WhereIf(tenantId.HasValue , x=>x.TenantId == tenantId)
                .CountAsync(cancellationToken);

            return count;
        }

        public async Task<List<UserTenant>> GetListAsync(string sorting = null, int maxResultCount = int.MaxValue, int skipCount = 0, Guid? userId = null, Guid? tenantId = null, CancellationToken cancellationToken = default)
        {
            var dbContext = await GetDbContextAsync();

            var entities = await dbContext.Set<UserTenant>().AsNoTracking()
                .WhereIf(userId.HasValue, x => x.UserId == userId)
                .WhereIf(tenantId.HasValue, x => x.TenantId == tenantId)
                .OrderBy<UserTenant>(sorting.IsNullOrWhiteSpace() ? "UserId" : sorting)
                .Skip(skipCount * maxResultCount).Take(maxResultCount)
                .ToListAsync(cancellationToken);

            return entities;
        }

        public async Task<UserTenant> FindAsync(Guid userId , Guid tenantId , Guid? targetUserId =null , CancellationToken cancellationToken = default)
        {
            var dbContext = await GetDbContextAsync();

            var entity = await dbContext.Set<UserTenant>().AsNoTracking()
                .WhereIf(userId !=default , x=>x.UserId == userId )
                .Where(x=>x.TenantId == tenantId)
                .WhereIf(targetUserId.HasValue , x=>x.TargetUserId == targetUserId)
                .FirstOrDefaultAsync();

            return entity;
        }
    }
}
